<template>
  <div class="ansible-audit-container">
    <!-- 星空背景 -->
    <div class="starry-background">
      <div class="stars"></div>
      <div class="stars2"></div>
      <div class="stars3"></div>
    </div>

    <!-- 主要内容区域 -->
    <div class="audit-content">
      <!-- 页面标题 -->
      <div class="page-header glass-effect">
        <div class="header-content">
          <div class="title-section">
            <h1 class="page-title">
              <i class="fa fa-users"></i>
              GitLab用户管理
            </h1>
            <p class="page-subtitle">管理GitLab用户和权限</p>
          </div>
          <div class="stats-section">
            <div class="stat-card glass-effect">
              <div class="stat-number">{{ (users || []).length || 0 }}</div>
              <div class="stat-label">用户总数</div>
            </div>
            <div class="stat-card glass-effect">
              <div class="stat-number">{{ (users || []).filter(u => u.state === 'active').length || 0 }}</div>
              <div class="stat-label">活跃用户</div>
            </div>
            <div class="stat-card glass-effect">
              <div class="stat-number">{{ (users || []).filter(u => u.is_admin).length || 0 }}</div>
              <div class="stat-label">管理员</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 工具栏：操作按钮 + 搜索过滤 -->
      <div class="search-filters glass-effect">
        <div class="toolbar-left">
          <el-button type="primary" @click="refreshUsers" class="glass-button refresh-button" :loading="loading">
            <i class="fa fa-refresh"></i>
            刷新用户
          </el-button>
          <el-button @click="syncUsers" class="glass-button sync-button" :loading="syncing">
            <i class="fa fa-sync"></i>
            同步用户
          </el-button>
          <el-button @click="showMappingModal" class="glass-button add-button">
            <i class="fa fa-link"></i>
            用户映射
          </el-button>
          <el-button @click="exportUsers" class="glass-button import-button">
            <i class="fa fa-download"></i>
            导出用户
          </el-button>
          <el-button @click="syncLocalUsersToGitlab" class="glass-button warning-button" :loading="syncingToGitlab">
            <i class="fa fa-upload"></i>
            同步到GitLab
          </el-button>
        </div>

        <div class="toolbar-right">
          <div class="search-group">
            <input
              v-model="searchText"
              type="text"
              class="glass-input"
              placeholder="搜索用户名或邮箱..."
            />
          </div>

          <div class="filter-group">
            <el-select
              v-model="selectedServer"
              @change="onServerChange"
              placeholder="请选择GitLab服务器"
              class="glass-select"
              clearable
            >
              <el-option
                v-for="server in gitlabServers"
                :key="server.id"
                :label="server.name"
                :value="server.id"
              />
            </el-select>
          </div>

          <div class="filter-group">
            <el-select
              v-model="mappingFilter"
              placeholder="所有用户"
              class="glass-select"
              clearable
            >
              <el-option label="所有用户" value="" />
              <el-option label="已映射" value="mapped" />
              <el-option label="未映射" value="unmapped" />
            </el-select>
          </div>
        </div>
      </div>

      <!-- 用户列表 -->
      <div class="users-table">
        <!-- 未选择服务器时的提示 -->
        <div v-if="!selectedServer" class="no-server-selected">
          <div class="empty-state">
            <i class="fa fa-gitlab"></i>
            <h3>请选择GitLab服务器</h3>
            <p>请先选择一个GitLab服务器来查看用户列表</p>
          </div>
        </div>

        <!-- 选择了服务器时显示用户列表 -->
        <template v-else>
          <div class="table-header">
            <div class="header-cell">GitLab用户</div>
            <div class="header-cell">本地用户</div>
            <div class="header-cell">服务器</div>
            <div class="header-cell">状态</div>
            <div class="header-cell">操作</div>
          </div>

          <div class="table-body">
            <div
              v-for="user in filteredUsers"
              :key="user.id"
              class="table-row"
            >
            <div class="table-cell">
              <div class="user-info">
                <div class="avatar">
                  <img v-if="user.avatar_url" :src="user.avatar_url" :alt="user.username" />
                  <i v-else class="fa fa-user"></i>
                </div>
                <div class="user-details">
                  <div class="username">{{ user.username }}</div>
                  <div class="email">{{ user.email }}</div>
                  <div class="name">{{ user.name }}</div>
                </div>
              </div>
            </div>

            <div class="table-cell">
              <div v-if="user.local_user" class="local-user">
                <div class="local-username">{{ user.local_user.username }}</div>
                <div class="local-name">{{ user.local_user.first_name }} {{ user.local_user.last_name }}</div>
              </div>
              <div v-else class="no-mapping">
                <span class="unmapped-text">未映射</span>
              </div>
            </div>

            <div class="table-cell">
              <span class="server-name">{{ user.gitlab_server_name }}</span>
            </div>

            <div class="table-cell">
              <span
                class="status-badge"
                :class="{ 'mapped': user.local_user, 'unmapped': !user.local_user }"
              >
                {{ user.local_user ? '已映射' : '未映射' }}
              </span>
            </div>

            <div class="table-cell">
              <div class="action-buttons-row">
                <button
                  v-if="!user.local_user"
                  class="action-btn primary-btn"
                  @click="mapUser(user)"
                  title="映射用户"
                >
                  <i class="fa fa-link"></i>
                  映射
                </button>
                <template v-else>
                  <button
                    class="action-btn edit-btn"
                    @click="editMapping(user)"
                    title="编辑映射"
                  >
                    <i class="fa fa-edit"></i>
                    编辑
                  </button>
                  <button
                    class="action-btn permission-btn"
                    @click="manageProjectPermissions(user)"
                    title="管理项目权限"
                  >
                    <i class="fa fa-cogs"></i>
                    项目权限
                  </button>
                  <button
                    class="action-btn danger-btn"
                    @click="unmapUser(user)"
                    title="取消映射"
                  >
                    <i class="fa fa-unlink"></i>
                    取消映射
                  </button>
                </template>
              </div>
            </div>
          </div>
        </div>

          <!-- 空状态 -->
          <div v-if="filteredUsers.length === 0" class="empty-state">
            <i class="fa fa-users empty-icon"></i>
            <h3>暂无用户数据</h3>
            <p>请先配置GitLab服务器，然后同步用户</p>
            <button class="glass-button primary" @click="syncUsers">
              <i class="fa fa-refresh"></i>
              同步用户
            </button>
          </div>
        </template>
      </div>
    </div>

    <!-- 用户映射模态框 -->
    <div v-if="mappingModalVisible" class="modal-overlay" @click="closeMappingModal">
      <div class="modal-content glass-container" @click.stop>
        <div class="modal-header">
          <h3>{{ isEditMapping ? '编辑' : '创建' }}用户映射</h3>
          <button class="close-btn" @click="closeMappingModal">
            <i class="fa fa-times"></i>
          </button>
        </div>

        <form @submit.prevent="saveMappingUser" class="mapping-form">
          <div class="form-group">
            <label>GitLab用户</label>
            <!-- 编辑模式：显示已选择的用户 -->
            <div v-if="isEditMapping && selectedGitLabUser" class="gitlab-user-display">
              <div class="avatar">
                <img v-if="selectedGitLabUser?.avatar_url" :src="selectedGitLabUser.avatar_url" :alt="selectedGitLabUser.username" />
                <i v-else class="fa fa-user"></i>
              </div>
              <div class="user-details">
                <div class="username">{{ selectedGitLabUser?.username }}</div>
                <div class="email">{{ selectedGitLabUser?.email }}</div>
              </div>
            </div>
            <!-- 创建模式：选择GitLab用户 -->
            <el-select
              v-else
              v-model="mappingForm.gitlab_user_id"
              placeholder="请选择GitLab用户"
              class="glass-select"
              style="width: 100%"
              clearable
              @change="onGitLabUserChange"
            >
              <el-option
                v-for="user in availableGitLabUsers"
                :key="user.id"
                :label="`${user.username} (${user.name}) - ${user.email}`"
                :value="user.id"
              >
                <div style="display: flex; align-items: center; gap: 8px;">
                  <img v-if="user.avatar_url" :src="user.avatar_url" style="width: 20px; height: 20px; border-radius: 50%;" />
                  <i v-else class="fa fa-user" style="width: 20px; text-align: center;"></i>
                  <div>
                    <div style="font-weight: 500;">{{ user.username }}</div>
                    <div style="font-size: 12px; color: #999;">{{ user.name }} - {{ user.email }}</div>
                  </div>
                </div>
              </el-option>
            </el-select>
          </div>

          <div class="form-group">
            <label>本地用户</label>
            <el-select
              v-model="mappingForm.local_user_id"
              placeholder="请选择本地用户"
              class="glass-select"
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="user in localUsers"
                :key="user.id"
                :label="`${user.username} (${user.first_name} ${user.last_name})`"
                :value="user.id"
              />
            </el-select>
          </div>

          <div class="form-actions">
            <button type="button" class="glass-button" @click="closeMappingModal">
              取消
            </button>
            <button type="submit" class="glass-button primary" :disabled="savingMapping">
              <i class="fa fa-save"></i>
              {{ savingMapping ? '保存中...' : '保存' }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- 项目权限管理模态框 -->
    <div v-if="projectPermissionModalVisible" class="modal-overlay" @click="closeProjectPermissionModal">
      <div class="modal-content glass-container large-modal" @click.stop>
        <div class="modal-header">
          <h3>管理项目权限 - {{ selectedUserForPermission?.username }}</h3>
          <button class="close-btn" @click="closeProjectPermissionModal">
            <i class="fa fa-times"></i>
          </button>
        </div>

        <div class="permission-content">
          <div class="user-info-section">
            <div class="user-avatar">
              <img v-if="selectedUserForPermission?.avatar_url" :src="selectedUserForPermission.avatar_url" :alt="selectedUserForPermission.username" />
              <i v-else class="fa fa-user"></i>
            </div>
            <div class="user-details">
              <h4>{{ selectedUserForPermission?.name }}</h4>
              <p>{{ selectedUserForPermission?.email }}</p>
              <span class="server-tag">{{ selectedUserForPermission?.gitlab_server_name }}</span>
            </div>
          </div>

          <div class="projects-section">
            <div class="section-header">
              <h4>项目权限设置</h4>
              <button class="glass-button small primary" @click="refreshProjects" :loading="loadingProjects">
                <i class="fa fa-refresh"></i>
                刷新项目
              </button>
            </div>

            <div class="projects-list">
              <div v-for="project in gitlabProjects" :key="project.id" class="project-item">
                <div class="project-info">
                  <div class="project-name">{{ project.name }}</div>
                  <div class="project-description">{{ project.description || '无描述' }}</div>
                </div>
                <div class="permission-controls">
                  <el-select
                    v-model="project.userAccessLevel"
                    placeholder="选择权限"
                    class="permission-select"
                    @change="updateProjectPermission(project)"
                  >
                    <el-option label="无权限" :value="0"></el-option>
                    <el-option label="Guest" :value="10"></el-option>
                    <el-option label="Reporter" :value="20"></el-option>
                    <el-option label="Developer" :value="30"></el-option>
                    <el-option label="Maintainer" :value="40"></el-option>
                    <el-option label="Owner" :value="50"></el-option>
                  </el-select>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="modal-footer">
          <button class="glass-button" @click="closeProjectPermissionModal">
            <i class="fa fa-times"></i>
            关闭
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { gitlabServerApi, gitlabUserApi, userApi } from '@/api/gitlab'
import { ElMessage, ElMessageBox, ElOption, ElSelect } from 'element-plus'
import { computed, onMounted, ref } from 'vue'

// 响应式数据
const users = ref([])
const localUsers = ref([])
const gitlabServers = ref([])
const searchText = ref('')
const selectedServer = ref('')
const mappingFilter = ref('')
const mappingModalVisible = ref(false)
const isEditMapping = ref(false)
const savingMapping = ref(false)
const selectedGitLabUser = ref(null)
const loading = ref(false)
const syncing = ref(false)
const syncingToGitlab = ref(false)

// 项目权限管理相关
const projectPermissionModalVisible = ref(false)
const selectedUserForPermission = ref(null)
const gitlabProjects = ref([])
const loadingProjects = ref(false)

const mappingForm = ref({
  gitlab_user_id: '',
  local_user_id: ''
})

// 计算属性
const filteredUsers = computed(() => {
  let filtered = users.value || []

  // 搜索过滤
  if (searchText.value) {
    const search = searchText.value.toLowerCase()
    filtered = filtered.filter(user =>
      user.username?.toLowerCase().includes(search) ||
      user.email?.toLowerCase().includes(search) ||
      user.name?.toLowerCase().includes(search) ||
      user.gitlab_server_name?.toLowerCase().includes(search)
    )
  }

  // 映射状态过滤
  if (mappingFilter.value === 'mapped') {
    filtered = filtered.filter(user => user.local_user)
  } else if (mappingFilter.value === 'unmapped') {
    filtered = filtered.filter(user => !user.local_user)
  }

  return filtered
})

// 可用的GitLab用户（未映射的用户）
const availableGitLabUsers = computed(() => {
  let filtered = users.value || []
  console.log('availableGitLabUsers 调试:', {
    totalUsers: filtered.length,
    users: filtered.map(u => ({ id: u.id, username: u.username, local_user: u.local_user }))
  })

  // 只显示未映射的用户
  const unmapped = filtered.filter(user => !user.local_user)
  console.log('未映射用户:', unmapped.length)
  return unmapped
})

// 方法
const syncUsers = async () => {
  if (!selectedServer.value) {
    ElMessage.warning('请先选择GitLab服务器')
    return
  }

  syncing.value = true
  try {
    // 调用API同步用户
    const response = await gitlabServerApi.syncUsers(selectedServer.value)

    if (response.data?.success) {
      ElMessage.success(`同步成功: ${response.data.message}`)
      // 重新加载用户列表
      await loadUsers()
    } else {
      throw new Error(response.data?.message || '同步失败')
    }
  } catch (error) {
    console.error('同步用户失败:', error)
    ElMessage.error(`同步用户失败: ${error.message || '未知错误'}`)
  } finally {
    syncing.value = false
  }
}

const showMappingModal = () => {
  console.log('showMappingModal 调试:', {
    totalUsers: users.value?.length || 0,
    availableUsers: availableGitLabUsers.value?.length || 0
  })
  isEditMapping.value = false
  selectedGitLabUser.value = null
  mappingForm.value = {
    gitlab_user_id: '',
    local_user_id: ''
  }
  mappingModalVisible.value = true
}

const mapUser = (user: any) => {
  isEditMapping.value = false
  selectedGitLabUser.value = user
  mappingForm.value = {
    gitlab_user_id: user.id,
    local_user_id: ''
  }
  mappingModalVisible.value = true
}

const editMapping = (user: any) => {
  isEditMapping.value = true
  selectedGitLabUser.value = user
  mappingForm.value = {
    gitlab_user_id: user.id,
    local_user_id: user.local_user?.id || ''
  }
  mappingModalVisible.value = true
}

const unmapUser = async (user: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消 "${user.username}" 的用户映射吗？`,
      '确认取消映射',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    // 调用API取消映射
    await gitlabUserApi.unmapUser(user.id)

    ElMessage.success('用户映射已取消')
    await loadUsers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消映射失败:', error)
      ElMessage.error('取消映射失败')
    }
  }
}

const closeMappingModal = () => {
  mappingModalVisible.value = false
}

const onGitLabUserChange = (userId) => {
  // 当选择GitLab用户时，更新selectedGitLabUser
  if (userId) {
    selectedGitLabUser.value = users.value.find(user => user.id === userId)
  } else {
    selectedGitLabUser.value = null
  }
}

const saveMappingUser = async () => {
  if (!mappingForm.value.gitlab_user_id) {
    ElMessage.warning('请选择GitLab用户')
    return
  }

  if (!mappingForm.value.local_user_id) {
    ElMessage.warning('请选择要映射的本地用户')
    return
  }

  savingMapping.value = true
  try {
    // 调用API保存用户映射
    await gitlabUserApi.mapToLocalUser(mappingForm.value.gitlab_user_id, {
      local_user_id: mappingForm.value.local_user_id
    })

    ElMessage.success('用户映射保存成功')
    closeMappingModal()
    await loadUsers()
  } catch (error) {
    console.error('保存映射失败:', error)
    ElMessage.error('保存映射失败')
  } finally {
    savingMapping.value = false
  }
}

const onServerChange = () => {
  // 服务器变化时重新加载用户列表
  loadUsers()
}

const exportUsers = () => {
  try {
    // 准备导出数据
    const exportData = filteredUsers.value.map(user => ({
      'GitLab用户名': user.username,
      '姓名': user.name,
      '邮箱': user.email,
      '状态': user.state,
      '是否管理员': user.is_admin ? '是' : '否',
      'GitLab服务器': user.gitlab_server_name || '',
      '本地用户': user.local_user ? `${user.local_user.username} (${user.local_user.first_name} ${user.local_user.last_name})` : '未映射',
      '映射状态': user.local_user ? '已映射' : '未映射'
    }))

    // 创建CSV内容
    const headers = Object.keys(exportData[0] || {})
    const csvContent = [
      headers.join(','),
      ...exportData.map(row => headers.map(header => `"${row[header] || ''}"`).join(','))
    ].join('\n')

    // 下载文件
    const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)
    link.setAttribute('download', `gitlab_users_${new Date().toISOString().split('T')[0]}.csv`)
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    ElMessage.success('用户数据导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

const syncLocalUsersToGitlab = async () => {
  if (!selectedServer.value) {
    ElMessage.warning('请先选择GitLab服务器')
    return
  }

  try {
    await ElMessageBox.confirm(
      '此操作将把本地用户同步到GitLab服务器，可能会创建新的GitLab用户账号。是否继续？',
      '确认同步',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    syncingToGitlab.value = true

    // 调用API同步本地用户到GitLab
    const response = await gitlabServerApi.syncLocalUsersToGitlab(selectedServer.value)

    if (response.data?.success) {
      ElMessage.success(`同步成功: ${response.data.message}`)
      // 重新加载用户列表
      await loadUsers()
    } else {
      throw new Error(response.data?.message || '同步失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('同步本地用户到GitLab失败:', error)
      ElMessage.error(`同步失败: ${error.message || '未知错误'}`)
    }
  } finally {
    syncingToGitlab.value = false
  }
}

const loadUsers = async () => {
  try {
    // 调用API获取GitLab用户列表
    const params = {}
    if (selectedServer.value) {
      params.gitlab_server_id = selectedServer.value
    }
    if (mappingFilter.value) {
      params.mapping_filter = mappingFilter.value
    }

    const response = await gitlabUserApi.getUsers(params)
    users.value = response.data?.results || []
  } catch (error) {
    console.error('加载用户列表失败:', error)
    ElMessage.error('加载用户列表失败')
  }
}

const refreshUsers = async () => {
  loading.value = true
  try {
    await loadUsers()
    ElMessage.success('用户列表刷新成功')
  } catch (error) {
    console.error('刷新用户失败:', error)
    ElMessage.error('刷新用户失败')
  } finally {
    loading.value = false
  }
}

const loadLocalUsers = async () => {
  try {
    // 调用API获取本地用户列表
    const response = await userApi.getUsers()
    localUsers.value = response.data?.results || []
  } catch (error) {
    console.error('加载本地用户列表失败:', error)
  }
}

const loadGitLabServers = async () => {
  try {
    // 调用API获取GitLab服务器列表
    const response = await gitlabServerApi.getServers()
    gitlabServers.value = response.data?.results || []
  } catch (error) {
    console.error('加载GitLab服务器列表失败:', error)
    ElMessage.error('加载GitLab服务器列表失败')
  }
}

// 项目权限管理
const manageProjectPermissions = async (user) => {
  selectedUserForPermission.value = user
  projectPermissionModalVisible.value = true
  await loadGitLabProjects()
}

const closeProjectPermissionModal = () => {
  projectPermissionModalVisible.value = false
  selectedUserForPermission.value = null
  gitlabProjects.value = []
}

const loadGitLabProjects = async () => {
  if (!selectedServer.value) {
    ElMessage.warning('请先选择GitLab服务器')
    return
  }

  loadingProjects.value = true
  try {
    // 获取GitLab项目列表
    const response = await gitlabServerApi.getProjects(selectedServer.value)
    gitlabProjects.value = response.data?.results || []

    // 获取用户在各个项目中的当前权限
    for (const project of gitlabProjects.value) {
      try {
        const membersResponse = await gitlabServerApi.getProjectMembers(selectedServer.value, project.id)
        const userMember = membersResponse.data?.find(member =>
          member.id === selectedUserForPermission.value.gitlab_id
        )
        project.userAccessLevel = userMember ? userMember.access_level : 0
      } catch (error) {
        console.warn(`获取项目 ${project.name} 成员失败:`, error)
        project.userAccessLevel = 0
      }
    }
  } catch (error) {
    console.error('加载GitLab项目失败:', error)
    ElMessage.error('加载GitLab项目失败')
  } finally {
    loadingProjects.value = false
  }
}

const refreshProjects = () => {
  loadGitLabProjects()
}

const updateProjectPermission = async (project) => {
  try {
    console.log('调试参数检查:', {
      selectedServer: selectedServer.value,
      projectId: project.id,
      selectedUserForPermission: selectedUserForPermission.value,
      userGitlabId: selectedUserForPermission.value?.gitlab_id,
      userAccessLevel: project.userAccessLevel,
      userAccessLevelType: typeof project.userAccessLevel
    })

    // 验证必要参数
    if (!selectedServer.value) {
      ElMessage.error('请先选择GitLab服务器')
      return
    }
    if (!project.id) {
      ElMessage.error('项目ID缺失')
      return
    }
    if (!selectedUserForPermission.value?.gitlab_id) {
      ElMessage.error('用户GitLab ID缺失')
      return
    }
    if (project.userAccessLevel === undefined || project.userAccessLevel === null) {
      ElMessage.error('权限级别缺失')
      return
    }

    console.log('更新项目权限参数:', {
      serverId: selectedServer.value,
      projectId: project.id,
      userId: selectedUserForPermission.value.gitlab_id,
      accessLevel: project.userAccessLevel,
      projectName: project.name
    })

    if (project.userAccessLevel === 0) {
      // 移除项目成员
      await gitlabServerApi.removeProjectMember(selectedServer.value, project.id, selectedUserForPermission.value.gitlab_id)
      ElMessage.success(`已移除用户在项目 ${project.name} 中的权限`)
    } else {
      // 添加或更新项目成员
      try {
        await gitlabServerApi.addProjectMember(selectedServer.value, project.id, selectedUserForPermission.value.gitlab_id, project.userAccessLevel)
        ElMessage.success(`已设置用户在项目 ${project.name} 中的权限`)
      } catch (error) {
        if (error.response?.status === 409) {
          // 用户已存在，更新权限
          await gitlabServerApi.updateProjectMember(selectedServer.value, project.id, selectedUserForPermission.value.gitlab_id, project.userAccessLevel)
          ElMessage.success(`已更新用户在项目 ${project.name} 中的权限`)
        } else {
          throw error
        }
      }
    }
  } catch (error) {
    console.error('更新项目权限失败:', error)
    ElMessage.error(`更新项目权限失败: ${error.response?.data?.message || error.message || '未知错误'}`)
    // 恢复原来的值
    await loadGitLabProjects()
  }
}

// 生命周期
onMounted(() => {
  loadUsers()
  loadLocalUsers()
  loadGitLabServers()
})
</script>

<style scoped>
/* 使用与Zabbix管理页面完全相同的样式 */
.ansible-audit-container {
  min-height: 100vh;
  background: linear-gradient(
    135deg,
    rgba(0, 0, 0, 0.9) 0%,
    rgba(20, 20, 40, 0.95) 50%,
    rgba(0, 0, 0, 0.9) 100%
  );
  overflow-x: hidden;
}

.starry-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg,
    rgba(0, 0, 0, 0.9) 0%,
    rgba(20, 20, 40, 0.95) 50%,
    rgba(0, 0, 0, 0.9) 100%
  );
  z-index: -1;
}

.starry-background::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image:
    radial-gradient(2px 2px at 20px 30px, #eee, transparent),
    radial-gradient(2px 2px at 40px 70px, rgba(255,255,255,0.8), transparent),
    radial-gradient(1px 1px at 90px 40px, #fff, transparent),
    radial-gradient(1px 1px at 130px 80px, rgba(255,255,255,0.6), transparent),
    radial-gradient(2px 2px at 160px 30px, rgba(255,255,255,0.4), transparent);
  background-repeat: repeat;
  background-size: 200px 200px;
  animation: twinkle 4s ease-in-out infinite alternate;
}

@keyframes twinkle {
  0% { opacity: 0.3; }
  100% { opacity: 1; }
}

.glass-container {
  background: rgba(164, 244, 186, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(164, 244, 186, 0.2);
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-title {
  color: #fff;
  font-size: 24px;
  font-weight: 600;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-filters {
  margin-bottom: 30px;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-radius: 12px;
}

.toolbar-left {
  display: flex;
  gap: 12px;
  align-items: center;
}

.toolbar-right {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.search-group {
  min-width: 200px;
}

.filter-group {
  min-width: 180px;
}

.glass-input {
  background: rgba(164, 244, 186, 0.1);
  border: 1px solid rgba(164, 244, 186, 0.3);
  border-radius: 8px;
  padding: 8px 12px;
  color: #fff;
  font-size: 14px;
  transition: all 0.3s ease;
  width: 100%;
}

.glass-input:focus {
  outline: none;
  border-color: rgba(164, 244, 186, 0.5);
  background: rgba(164, 244, 186, 0.15);
}

.glass-input::placeholder {
  color: rgba(255, 255, 255, 0.5);
}



.users-table {
  background: rgba(164, 244, 186, 0.05);
  border: 1px solid rgba(164, 244, 186, 0.2);
  border-radius: 12px;
  overflow-x: auto;
  min-width: 0;
}

.table-header {
  display: grid;
  grid-template-columns: 2fr 2fr 1fr 1fr 1.5fr;
  background: rgba(164, 244, 186, 0.1);
  border-bottom: 1px solid rgba(164, 244, 186, 0.2);
  min-width: 1000px;
}

.header-cell {
  padding: 16px;
  color: #fff;
  font-weight: 600;
  font-size: 14px;
}

.table-body {
  max-height: 600px;
  overflow-y: auto;
}

.table-row {
  display: grid;
  grid-template-columns: 2fr 2fr 1fr 1fr 1.5fr;
  border-bottom: 1px solid rgba(164, 244, 186, 0.1);
  transition: all 0.3s ease;
  min-width: 1000px;
}

.table-row:hover {
  background: rgba(164, 244, 186, 0.05);
}

.table-cell {
  padding: 16px;
  display: flex;
  align-items: center;
}

.table-cell:last-child {
  min-width: 350px;
  width: 350px;
  flex-shrink: 0;
  position: relative;
  z-index: 10;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: rgba(164, 244, 186, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar i {
  color: rgba(255, 255, 255, 0.7);
  font-size: 18px;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.username {
  color: #fff;
  font-weight: 600;
  font-size: 14px;
}

.email {
  color: rgba(255, 255, 255, 0.7);
  font-size: 12px;
}

.name {
  color: rgba(255, 255, 255, 0.6);
  font-size: 12px;
}

.local-user {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.local-username {
  color: #fff;
  font-weight: 600;
  font-size: 14px;
}

.local-name {
  color: rgba(255, 255, 255, 0.7);
  font-size: 12px;
}

.no-mapping {
  display: flex;
  align-items: center;
}

.unmapped-text {
  color: rgba(255, 255, 255, 0.5);
  font-style: italic;
}

.server-name {
  color: rgba(255, 255, 255, 0.8);
  font-size: 14px;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.mapped {
  background: rgba(74, 222, 128, 0.2);
  color: #4ade80;
  border: 1px solid rgba(74, 222, 128, 0.3);
}

.status-badge.unmapped {
  background: rgba(156, 163, 175, 0.2);
  color: #9ca3af;
  border: 1px solid rgba(156, 163, 175, 0.3);
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.action-buttons-row {
  display: flex;
  gap: 6px;
  align-items: center;
  justify-content: flex-start;
  flex-wrap: nowrap;
  min-width: 280px;
}

.action-btn {
  background: rgba(164, 244, 186, 0.1) !important;
  border: 1px solid rgba(164, 244, 186, 0.3) !important;
  border-radius: 6px !important;
  color: #a4f4ba !important;
  padding: 6px 12px !important;
  cursor: pointer !important;
  transition: all 0.3s ease !important;
  font-size: 12px !important;
  font-weight: 500 !important;
  display: inline-flex !important;
  align-items: center !important;
  gap: 4px !important;
  white-space: nowrap !important;
  backdrop-filter: blur(10px) !important;
  min-width: 85px !important;
  width: auto !important;
  justify-content: center !important;
  text-align: center !important;
}

.action-btn:hover {
  background: rgba(164, 244, 186, 0.2) !important;
  border-color: rgba(164, 244, 186, 0.6) !important;
  transform: translateY(-1px) !important;
  box-shadow: 0 4px 12px rgba(164, 244, 186, 0.2) !important;
}

.action-btn i {
  font-size: 11px !important;
}

.primary-btn {
  background: rgba(34, 197, 94, 0.15) !important;
  border-color: rgba(34, 197, 94, 0.4) !important;
  color: #22c55e !important;
}

.primary-btn:hover {
  background: rgba(34, 197, 94, 0.25) !important;
  border-color: rgba(34, 197, 94, 0.6) !important;
  box-shadow: 0 4px 12px rgba(34, 197, 94, 0.3) !important;
}

.edit-btn {
  background: rgba(59, 130, 246, 0.15) !important;
  border-color: rgba(59, 130, 246, 0.4) !important;
  color: #3b82f6 !important;
}

.edit-btn:hover {
  background: rgba(59, 130, 246, 0.25) !important;
  border-color: rgba(59, 130, 246, 0.6) !important;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3) !important;
}

.permission-btn {
  background: rgba(245, 158, 11, 0.15) !important;
  border-color: rgba(245, 158, 11, 0.4) !important;
  color: #f59e0b !important;
}

.permission-btn:hover {
  background: rgba(245, 158, 11, 0.25) !important;
  border-color: rgba(245, 158, 11, 0.6) !important;
  box-shadow: 0 4px 12px rgba(245, 158, 11, 0.3) !important;
}

.danger-btn {
  background: rgba(239, 68, 68, 0.15) !important;
  border-color: rgba(239, 68, 68, 0.4) !important;
  color: #ef4444 !important;
}

.danger-btn:hover {
  background: rgba(239, 68, 68, 0.25) !important;
  border-color: rgba(239, 68, 68, 0.6) !important;
  box-shadow: 0 4px 12px rgba(239, 68, 68, 0.3) !important;
}

.glass-button {
  background: rgba(164, 244, 186, 0.15);
  border: 1px solid rgba(164, 244, 186, 0.4);
  border-radius: 8px;
  color: #a4f4ba;
  padding: 8px 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
  backdrop-filter: blur(5px);
  box-shadow: 0 4px 15px rgba(164, 244, 186, 0.1);
  position: relative;
  z-index: 1;
}

.glass-button:hover {
  background: rgba(164, 244, 186, 0.25);
  border-color: rgba(164, 244, 186, 0.6);
  color: #fff;
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(164, 244, 186, 0.2);
}

.glass-button.primary {
  background: rgba(164, 244, 186, 0.25);
  border-color: rgba(164, 244, 186, 0.6);
  color: #fff;
  box-shadow: 0 4px 15px rgba(164, 244, 186, 0.2);
}

.glass-button.small {
  padding: 4px 8px;
  font-size: 12px;
}

.glass-button.danger {
  background: rgba(255, 99, 99, 0.2);
  border-color: rgba(255, 99, 99, 0.3);
}

.glass-button.danger:hover {
  background: rgba(255, 99, 99, 0.3);
  border-color: rgba(255, 99, 99, 0.5);
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: rgba(255, 255, 255, 0.7);
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-state h3 {
  color: #fff;
  margin-bottom: 8px;
}

.empty-state p {
  margin-bottom: 24px;
}

/* 未选择服务器状态样式 */
.no-server-selected {
  padding: 40px 20px;
}

.no-server-selected .empty-state {
  padding: 40px 20px;
}

.no-server-selected .empty-state i {
  font-size: 64px;
  color: rgba(164, 244, 186, 0.6);
  margin-bottom: 20px;
}

.no-server-selected .empty-state h3 {
  color: rgba(164, 244, 186, 0.9);
  font-size: 20px;
  margin-bottom: 10px;
}

.no-server-selected .empty-state p {
  color: rgba(255, 255, 255, 0.7);
  font-size: 16px;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.modal-header h3 {
  color: #fff;
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  color: rgba(255, 255, 255, 0.7);
  font-size: 18px;
  cursor: pointer;
  padding: 4px;
}

.close-btn:hover {
  color: #fff;
}

.mapping-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  color: rgba(255, 255, 255, 0.9);
  font-size: 14px;
  font-weight: 500;
}

.gitlab-user-display {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: rgba(164, 244, 186, 0.05);
  border: 1px solid rgba(164, 244, 186, 0.2);
  border-radius: 8px;
}

.form-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 8px;
}

.starry-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
  pointer-events: none;
}

.stars, .stars2, .stars3 {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: transparent;
}

.stars {
  background-image:
    radial-gradient(2px 2px at 20px 30px, #eee, transparent),
    radial-gradient(2px 2px at 40px 70px, rgba(255,255,255,0.8), transparent),
    radial-gradient(1px 1px at 90px 40px, #fff, transparent);
  background-repeat: repeat;
  background-size: 200px 100px;
  animation: zoom 20s infinite linear;
}

.stars2 {
  background-image:
    radial-gradient(1px 1px at 40px 60px, #fff, transparent),
    radial-gradient(1px 1px at 120px 10px, rgba(255,255,255,0.7), transparent);
  background-repeat: repeat;
  background-size: 300px 200px;
  animation: zoom 40s infinite linear;
}

.stars3 {
  background-image:
    radial-gradient(1px 1px at 10px 10px, rgba(255,255,255,0.5), transparent);
  background-repeat: repeat;
  background-size: 400px 300px;
  animation: zoom 60s infinite linear;
}

@keyframes zoom {
  from { transform: scale(1); }
  to { transform: scale(1.5); }
}

.audit-content {
  position: relative;
  z-index: 10;
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.glass-effect {
  background: rgba(164, 244, 186, 0.1);
  border: 1px solid rgba(164, 244, 186, 0.2);
  border-radius: 12px;
  backdrop-filter: blur(20px);
  box-shadow:
    0 8px 32px rgba(0, 0, 0, 0.3),
    inset 0 1px 0 rgba(255, 255, 255, 0.1);
}

.page-header {
  margin-bottom: 30px;
  padding: 30px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 30px;
}

.title-section h1 {
  color: rgba(255, 255, 255, 0.95);
  font-size: 28px;
  font-weight: 600;
  margin: 0 0 8px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.title-section h1 i {
  color: #a4f4ba;
  margin-right: 12px;
}

.page-subtitle {
  color: rgba(255, 255, 255, 0.7);
  font-size: 14px;
  margin: 0;
}

.stats-section {
  display: flex;
  gap: 20px;
}

.stat-card {
  padding: 20px;
  text-align: center;
  min-width: 120px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #a4f4ba;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
  text-transform: uppercase;
  letter-spacing: 0.5px;
}



/* 工具栏按钮样式 - 完全照抄Zabbix页面 */
.glass-button {
  background: rgba(164, 244, 186, 0.15) !important;
  border: 1px solid rgba(164, 244, 186, 0.3) !important;
  color: rgba(255, 255, 255, 0.9) !important;
  transition: all 0.3s ease !important;
  backdrop-filter: blur(10px) !important;
  border-radius: 8px !important;
  padding: 8px 16px !important;
  font-size: 14px !important;
  font-weight: 500 !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;

  &:hover {
    background: rgba(164, 244, 186, 0.25) !important;
    border-color: rgba(164, 244, 186, 0.5) !important;
    color: #ffffff !important;
    box-shadow: 0 4px 16px rgba(164, 244, 186, 0.2) !important;
  }

  i {
    margin-right: 6px !important;
    color: #00eaff !important;
  }

  &.refresh-button {
    background: rgba(138, 43, 226, 0.2) !important;
    border-color: rgba(138, 43, 226, 0.4) !important;
    color: #ffffff !important;

    &:hover {
      background: rgba(138, 43, 226, 0.3) !important;
      border-color: rgba(138, 43, 226, 0.6) !important;
      box-shadow: 0 4px 16px rgba(138, 43, 226, 0.3) !important;
    }

    i {
      color: #8a2be2 !important;
    }
  }

  &.sync-button {
    background: rgba(59, 130, 246, 0.2) !important;
    border-color: rgba(59, 130, 246, 0.4) !important;
    color: #ffffff !important;

    &:hover {
      background: rgba(59, 130, 246, 0.3) !important;
      border-color: rgba(59, 130, 246, 0.6) !important;
      box-shadow: 0 4px 16px rgba(59, 130, 246, 0.3) !important;
    }

    i {
      color: #3b82f6 !important;
    }
  }

  &.add-button {
    background: rgba(34, 197, 94, 0.2) !important;
    border-color: rgba(34, 197, 94, 0.4) !important;
    color: #ffffff !important;

    &:hover {
      background: rgba(34, 197, 94, 0.3) !important;
      border-color: rgba(34, 197, 94, 0.6) !important;
      box-shadow: 0 4px 16px rgba(34, 197, 94, 0.3) !important;
    }

    i {
      color: #22c55e !important;
    }
  }

  &.import-button {
    background: rgba(6, 182, 212, 0.2) !important;
    border-color: rgba(6, 182, 212, 0.4) !important;
    color: #ffffff !important;

    &:hover {
      background: rgba(6, 182, 212, 0.3) !important;
      border-color: rgba(6, 182, 212, 0.6) !important;
      box-shadow: 0 4px 16px rgba(6, 182, 212, 0.3) !important;
    }

    i {
      color: #06b6d4 !important;
    }
  }

  &.delete-button {
    background: rgba(239, 68, 68, 0.2) !important;
    border-color: rgba(239, 68, 68, 0.4) !important;
    color: #ffffff !important;

    &:hover {
      background: rgba(239, 68, 68, 0.3) !important;
      border-color: rgba(239, 68, 68, 0.6) !important;
      box-shadow: 0 4px 16px rgba(239, 68, 68, 0.3) !important;
    }

    i {
      color: #ef4444 !important;
    }
  }
}

/* Element Plus 选择器样式覆盖 - 使用超透明样式 */
:deep(.el-select) {
  .el-input__wrapper {
    background: rgba(164, 244, 186, 0.1) !important;
    border: 1px solid rgba(164, 244, 186, 0.3) !important;
    border-radius: 8px !important;
    box-shadow: none !important;
  }

  .el-input__inner {
    background: transparent !important;
    color: #fff !important;
  }

  &:hover .el-input__wrapper {
    border-color: rgba(164, 244, 186, 0.5) !important;
  }

  &.is-focused .el-input__wrapper {
    border-color: rgba(164, 244, 186, 0.5) !important;
    background: rgba(164, 244, 186, 0.15) !important;
  }
}

:deep(.el-input) {
  .el-input__wrapper {
    background: rgba(164, 244, 186, 0.1) !important;
    border: 1px solid rgba(164, 244, 186, 0.3) !important;
    border-radius: 8px !important;
    box-shadow: none !important;
  }

  .el-input__inner {
    background: transparent !important;
    color: #fff !important;
  }

  &:hover .el-input__wrapper {
    border-color: rgba(164, 244, 186, 0.5) !important;
  }

  &.is-focus .el-input__wrapper {
    border-color: rgba(164, 244, 186, 0.5) !important;
    background: rgba(164, 244, 186, 0.15) !important;
  }
}

:deep(.el-select-dropdown) {
  background: rgba(30, 30, 30, 0.95) !important;
  border: 1px solid rgba(164, 244, 186, 0.3) !important;
  border-radius: 8px !important;
}

:deep(.el-select-dropdown__item) {
  color: rgba(255, 255, 255, 0.8) !important;

  &:hover {
    background: rgba(164, 244, 186, 0.1) !important;
  }

  &.selected {
    background: rgba(164, 244, 186, 0.2) !important;
    color: #a4f4ba !important;
  }
}

/* 项目权限管理模态框样式 */
.large-modal {
  width: 90%;
  max-width: 800px;
  max-height: 80vh;
  overflow-y: auto;
}

.permission-content {
  padding: 20px 0;
}

.user-info-section {
  display: flex;
  align-items: center;
  padding: 20px;
  background: rgba(164, 244, 186, 0.05);
  border-radius: 12px;
  margin-bottom: 30px;
  border: 1px solid rgba(164, 244, 186, 0.2);
}

.user-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 20px;
  background: rgba(164, 244, 186, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  i {
    font-size: 24px;
    color: #a4f4ba;
  }
}

.user-details {
  h4 {
    margin: 0 0 5px 0;
    color: #a4f4ba;
    font-size: 18px;
  }

  p {
    margin: 0 0 10px 0;
    color: rgba(255, 255, 255, 0.7);
    font-size: 14px;
  }
}

.server-tag {
  background: rgba(164, 244, 186, 0.2);
  color: #a4f4ba;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  border: 1px solid rgba(164, 244, 186, 0.3);
}

.projects-section {
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h4 {
      margin: 0;
      color: #a4f4ba;
      font-size: 16px;
    }
  }
}

.projects-list {
  max-height: 400px;
  overflow-y: auto;
}

.project-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background: rgba(164, 244, 186, 0.03);
  border: 1px solid rgba(164, 244, 186, 0.1);
  border-radius: 8px;
  margin-bottom: 10px;
  transition: all 0.3s ease;

  &:hover {
    background: rgba(164, 244, 186, 0.08);
    border-color: rgba(164, 244, 186, 0.2);
  }
}

.project-info {
  flex: 1;

  .project-name {
    font-weight: 500;
    color: #a4f4ba;
    margin-bottom: 5px;
  }

  .project-description {
    font-size: 12px;
    color: rgba(255, 255, 255, 0.6);
  }
}

.permission-controls {
  .permission-select {
    width: 150px;
  }
}


</style>
